<template>
  <div class="chat-page">
    <div class="chat-box">
      <!-- 左侧用户信息 -->
      <div class="user-profile">
        <div class="profile">
          <img class="avatar" :src="user.user.avatar" />
          <div class="username">
            {{ user.user.nickName || "---" }}
          </div>
        </div>
        <div class="menu">
          <div
            :class="['menu-item', { act: active_menu == 'chat' }]"
            @click="active_menu = 'chat'"
          >
            <div class="icon">
              <el-icon :size="16"><chat-square></chat-square></el-icon>
            </div>
            <div class="item-title">聊天</div>
          </div>
          <div
            :class="['menu-item', { act: active_menu == 'setting' }]"
            @click="active_menu = 'setting'"
          >
            <div class="icon">
              <el-icon :size="16">
                <setting></setting>
              </el-icon>
            </div>
            <div class="item-title">系统设置</div>
          </div>
        </div>
      </div>
      <!-- 聊天窗口 -->
      <div class="user-chat-frame">
        <header class="frame-header">
          <div class="tip-msg">
            <el-badge :is-dot="true" :offset="[-3, 2]">
              <el-icon :size="22" color="#555">
                <bell></bell>
              </el-icon>
            </el-badge>
          </div>
        </header>
        <transition name="chat">
          <div class="chat-frame" v-if="active_menu == 'chat'">
            <div class="chat-header">
              <span>聊天</span>
            </div>
            <!-- 聊天框核心区域布局 -->
            <div class="chat-content">
              <!-- 左侧用户列表区域 -->
              <div class="friend-view-area">
                <div class="friend-search">
                  <el-input
                    class="search"
                    placeholder="搜索朋友"
                    suffix-icon="Search"
                  />
                </div>
                <div class="friend-list">
                  <div
                    class="friend-list-item"
                    v-for="(item, index) in friendList"
                    :key="index"
                  >
                    <div class="friend-avatar">
                      <img :src="item.avatar || '/images/profile.jpg'" />
                    </div>
                    <div class="friend-nick">{{item.nickName || "test"}}</div>
                    <div class="friend-online">
                      <el-icon v-if="item.online == 2" size="18" color="#00CC22"
                        ><success-filled></success-filled
                      ></el-icon>
                      <el-icon v-if="item.online == 1" size="18" color="#FF2222"
                        ><warning-filled></warning-filled></el-icon>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 右侧聊天区域 -->
              <div class="chat-window">
                <div class="chat-window-header">
                  <span class="title">Kelly Games</span>
                  <span class="tips">{{ wsStore.line_msg }}</span>
                </div>
                <div class="chat-window-box">
                  <div class="chat-list" id="chat-list">
                    <div
                      :class="[
                        'chat-list-item',
                        { left: index % 2 === 0 },
                        { right: index % 2 === 1 },
                      ]"
                      v-for="(item, index) in chat_list_data"
                      :key="index"
                    >
                      <div class="avatar">
                        <img
                          :src="
                            index % 2 === 0
                              ? '/images/profile.jpg'
                              : '/images/logo1.png'
                          "
                        />
                      </div>
                      <div class="content-area">
                        <div class="item-context">
                          {{ item.text }}
                        </div>
                        <div class="item-time">
                          {{ item.time}}
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="input-area">
                    <el-input
                      class="enter-inp"
                      placeholder="输入发送的消息"
                      v-model="msg"
                    >
                      <template #prefix>
                        <!-- <el-icon :size="20" color="#2B5DFFCC"><Microphone></Microphone></el-icon> -->
                        <span class="icon iconfont" style="color: #d224ff"
                          >&#xe62a;</span
                        >
                      </template>
                      <template #suffix>
                        <span class="icon iconfont">&#xe8ab;</span>
                        <span class="icon iconfont" style="font-size: 18px"
                          >&#xe67f;</span
                        >
                        <span
                          class="icon iconfont"
                          style="color: #2b5dffcc; font-size: 22px"
                          @click="sendMsg"
                          >&#xe622;</span
                        >
                        <!-- <el-icon :size="20" color="#D224FFCC"><Promotion/></el-icon> -->
                      </template>
                    </el-input>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="setting-frame" v-else>
            <div class="chat-header">
              <span>系统设置</span>
              <div class="action" v-if="!is_edit" @click="is_edit = true">
                <el-icon :size="22" color="#2B5DFF">
                  <edit></edit>
                </el-icon>
              </div>
            </div>
            <div class="setting-content">
              <el-form label-width="15%">
                <el-form-item label="昵称">
                  <span v-if="!is_edit">{{ userinfo.nickName }}</span>
                  <el-input
                    class="user-inp"
                    placeholder="请输入昵称"
                    v-else
                    v-model="userinfo.nickName"
                  />
                </el-form-item>
                <el-form-item label="账号">
                  <span v-if="!is_edit">{{ userinfo.username }}</span>
                  <el-input
                    class="user-inp"
                    placeholder="请输入昵称"
                    v-else
                    v-model="userinfo.username"
                  />
                </el-form-item>
                <el-form-item label="头像">
                  <img
                    class="ava-img"
                    :src="userinfo.avatar || '/images/profile.jpg'"
                    v-if="!is_edit"
                  />
                  <el-upload
                    class="avatar"
                    v-else
                    :action="`/api/oss/upload/file`"
                    :show-file-list="false"
                    :on-success="uploadSuccess"
                  >
                    <img
                      :src="userinfo.avatar"
                      class="img"
                      v-if="userinfo.avatar"
                    />
                    <el-icon v-else :size="25">
                      <plus></plus>
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="性别">
                  <template v-if="!is_edit">
                    <span class="span-icon" v-if="userinfo.gender == 1"
                      ><el-icon :size="20" color="#2B5DFF">
                        <male></male> </el-icon
                      >男</span
                    >
                    <span class="span-icon" v-if="userinfo.gender == 2"
                      ><el-icon :size="20" color="#D224FF">
                        <female></female> </el-icon
                      >女</span
                    >
                  </template>
                  <el-radio-group v-model="userinfo.gender" v-else>
                    <el-radio :value="1">男</el-radio>
                    <el-radio :value="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="在线状态">
                  <span class="span-icon" v-if="userinfo.online == 2">
                    <el-icon :size="20" color="#008800"
                      ><success-filled></success-filled
                    ></el-icon>
                    在线
                  </span>
                  <span class="span-icon" v-if="userinfo.online == 1">
                    <el-icon :size="20" color="#A00000"
                      ><warning-filled></warning-filled
                    ></el-icon>
                    离线
                  </span>
                </el-form-item>
                <el-form-item v-if="is_edit">
                  <el-button class="out-btn" @click="doEdit"
                    >更新信息</el-button
                  >
                </el-form-item>
                <el-form-item>
                  <el-button class="out-btn" @click="logout"
                    >退出登录</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
          </div>
        </transition>
      </div>
      <!-- 聊天窗口 -->
    </div>
  </div>
</template>
<script>
import { defineComponent } from "vue";
import { getToken } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
import { updateUser } from "@/api/login";
import { Picture, Promotion } from "@element-plus/icons-vue";
export default defineComponent({
  beforeRouteEnter(to, from, next) {
    let token = getToken();
    if (!token) {
      next("/login");
    }
    next();
  },
});
</script>
<script setup>
import useUserStore from "@/store/modules/user";
import { nextTick, onMounted } from "vue";
import { useRouter } from "vue-router";
import useWebsocketStore from "@/store/modules/ws";
import {getChatUsers} from "@/api/login";
import { ref } from "vue";
const user = useUserStore();
const router = useRouter();
//连接websocket开始发送消息的操作
const wsStore = useWebsocketStore();
//服务器地址的配置信息
const server_url = import.meta.env.VITE_APP_SERVER_URL;
const chat_list_data = ref([
  {
    id: 1,
    text: "你好，很高兴认识你!!",
    time: "2024-11-25 10:00:00",
  },
  {
    id: 2,
    text: "你好，很高兴认识你!!",
    time: "2024-11-25 10:00:00",
  },
  {
    id: 3,
    text: "吃饭了吗!!",
    time: "2024-11-25 10:00:00",
  },
  {
    id: 4,
    text: "吃了，你呢!!",
    time: "2024-11-25 10:00:00",
  },
]);
//发送消息的文本框
const msg = ref("");
let active_menu = ref("chat");
let is_edit = ref(false); //是否编辑状态
let userinfo = ref({
  id: user.user.id,
  nickName: user.user.nickName,
  username: user.user.username,
  gender: user.user.gender,
  avatar: user.user.avatar,
  status: user.user.status,
  online: user.user.online,
});

const logout = async () => {
  ElMessageBox.confirm("确定要退出吗")
    .then(async (respons) => {
      console.log("触发点击事件");
      let res = await user.logout();
      if (res.code === 200) {
        //关闭连接，自动下线
        wsStore.ws.close();
        router.push("/login");
      }
    })
    .catch((res) => {
      console.log("取消退出");
    });
};

//文件上传成功后的效果
const uploadSuccess = (file) => {
  console.log("文件上传成功", file);
  if (file.code === 200) {
    userinfo.value.avatar = file?.data?.path;
  }
};

// 执行编辑的过程
const doEdit = async () => {
  //请求编辑的api接口
  let res = await updateUser(userinfo.value);

  if (res.code === 200) {
    ElMessage.success("更新信息成功");

    user.getUser(); //重新获取一下当前用户的信息数据
  }
  is_edit.value = false;
};

//监听页面滚动效果
const chat_list_scroll = () => {
  nextTick(() => {
    let chat_list = document.getElementById("chat-list");
    console.log(
      "聊天列表--数据",
      chat_list.scrollHeight,
      chat_list.scrollTop,
      chat_list.offsetHeight
    );
    chat_list.scrollTop = chat_list.scrollHeight - chat_list.offsetHeight;
  });
};

const sendMsg = () => {
  if (msg.value.length < 0) {
    ElMessage.error("请输入消息");
    return false;
  }

  //开始发送消息了
  let sData = JSON.stringify({to:3,from:1,message:msg.value,type:'chat'});
  wsStore.ws.send(sData);

  chat_list_data.value.push({
    id: chat_list_data.value.length + 1,
    text: msg.value,
    time: new Date().toLocaleDateString().replace(/\//g, "-"),
  });
  chat_list_scroll();
};
const init_websocket = ()=>{
  wsStore.online();
  wsStore.ws.onopen(()=>{
    wsStore.line_msg = "连接成功!!"
  })

  wsStore.ws.onmessage((event)=>{
    //不等于心跳检测方法的逻辑继续执行
    if(event.data !== "pang"){
      let data = JSON.parse(event.data);

      //这个说明是，公共消息，来个提示信息即可
      if(data.type == "publish" || data.type == "connect"){
        ElMessage(data.msg);
        wsStore.line_msg = `共${data.onlineNum}人在线`
      }
    }
  })

  wsStore.ws.connect();
}

//左侧用户列表区域效果展示
let friendList = ref([]);
const getFriendList = async ()=>{
  let res = await getChatUsers();
  console.log("获取好友列表----",res);
  if(res.code === 200){
    friendList.value = res.data;

    friendList.value.sort((a,b)=>{
      return b.online - a.online;
    })
  }
}

onMounted(() => {
  chat_list_scroll();
  init_websocket();
  getFriendList();
});
</script>
<style lang="scss" scoped>
@import "@/assets/style/chat.scss";
</style>